#include<iostream>
#include <vector>
using namespace std;
class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) {
        int n = matrix.size();
        if (matrix.empty() || matrix[0].empty())
            return 0;
        vector<vector<int>> dp(n, vector<int>(n, 0));
        for (int i = 0; i < n; i++) {
            dp[0][i] = matrix[0][i];
        }
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int minPrev = dp[i - 1][j];
                if (j > 0) {
                    minPrev = min(minPrev, dp[i - 1][j - 1]);
                }
                if (j < n - 1) {
                    minPrev = min(minPrev, dp[i - 1][j + 1]);
                }

                dp[i][j] = minPrev + matrix[i][j];
            }
        }
        int minnum = INT_MAX;
        for (int j = 0; j < n; j++) {
            minnum = min(minnum, dp[n - 1][j]);
        }
        return minnum;
    }
};